package main

import (
	"abss/utils"
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"syscall"
	"time"

	"github.com/gonutz/w32/v2"
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
)

const (
	KEYCODE_DPAD_UP    string = "19"
	KEYCODE_DPAD_DOWN  string = "20"
	KEYCODE_DPAD_LEFT  string = "21"
	KEYCODE_DPAD_RIGHT string = "22"
)

var (
	InfoReleasePackageName    = ""
	InfoReleaseProgrammeName  = ""
	InfoReleasePlayerName     = ""
	InstallUtilsPackageName   = ""
	InstallUtilsProgrammeName = ""
	AdbToolPath               = "./adb.exe"
	AdbToolPoint              = "-s"
	DeviceName                = ""
	AdbToolShell              = "shell"
)

// 主容器
type MyMainWindow struct {
	*walk.MainWindow
	te1                                                             *walk.TextEdit
	connBtn, irBtn1, irBtn2, irBtn3, irBtn4, fzBtn1, fzBtn2, fzBtn3 *walk.PushButton
	// adb连接状态，信发当前运行，辅助安装，是否是M3,是否ROOT
	sbi, sbi2, sbi3, sbi4, sbi5 *walk.StatusBarItem
	connSelect, l3cb            *walk.ComboBox
	ipAddr                      *walk.LineEdit
	start, stop                 *walk.Icon
	screen                      *walk.ImageView
	cs1, rme                    *walk.Composite
	dlgrm                       *walk.Dialog
	// l1 设备型号
	// l2 IP地址
	// l3 MAC地址
	// l4 信发版本
	// l5 辅助安装版本
	// l6 接入网络模式
	// l7 设备分辨率
	// l8 显示屏接入数量
	// l9 安卓版本
	l1, l2, l3, l4, l5, l6, l7, l8, l9 *walk.Label
}

// 设备信息
type Device struct {
	Name  string
	State string
}

// 网卡列表
var netList = make([]string, 0, 10)

// 显示屏列表
var displayList = make([]string, 0, 10)

// 选项
var connIdx = 0

var connDeviceList = make([]Device, 0, 10)

// 隐藏cmd
func hideConsole() {
	console := w32.GetConsoleWindow()
	if console == 0 {
		return
	}
	_, consoleProcID := w32.GetWindowThreadProcessId(console)
	if w32.GetCurrentProcessId() == consoleProcID {
		w32.ShowWindowAsync(console, w32.SW_HIDE)
	}
}

func main() {
	hideConsole()
	mw := new(MyMainWindow)
	netList = append(netList, "wlan0")
	icon1, err := walk.NewIconFromFile("img/check.ico")
	if err != nil {
		log.Fatal(err)
	}
	mw.start = icon1
	icon2, err := walk.NewIconFromFile("img/stop.ico")
	if err != nil {
		log.Fatal(err)
	}
	mw.stop = icon2

	adbDeviceList()

	if _, err := (MainWindow{
		AssignTo: &mw.MainWindow,
		Title:    "ABSS -- V1.0.1 作者: zebias Golang",
		MinSize:  Size{Width: 100, Height: 100},
		Size:     Size{Width: 1200, Height: 800},
		MaxSize:  Size{Width: 1200, Height: 800},
		Layout:   VBox{},
		// MenuItems: []MenuItem{
		// 	Menu{
		// 		Text: "功能",
		// 		Items: []MenuItem{
		// 			Action{
		// 				Text: "远程",
		// 			},
		// 		},
		// 	},
		// },
		Children: []Widget{
			// PushButton{
			// 	Text: "查看日志",
			// 	OnClicked: func() {
			// 		cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName,"shell", "cat", "proc/meminfo")
			// 		output, err := cmd.Output()
			// 		if err != nil {
			// 			log.Fatal(err)
			// 		}
			// 		outTE.SetText(string(output))
			// 	},
			// },
			HSplitter{
				// 分界线宽度
				HandleWidth: 1,
				MaxSize:     Size{Width: 30},
				MinSize:     Size{Width: 30},
				Children: []Widget{
					Composite{
						Layout:        Grid{Columns: 1},
						MinSize:       Size{Width: 100, Height: 50},
						StretchFactor: 1,
						Name:          "测试",
						Children: []Widget{
							GroupBox{
								Layout: VBox{},
								Title:  "设备列表",
								Children: []Widget{
									Composite{
										MinSize: Size{Width: 100},
										Layout:  HBox{},
										Children: []Widget{
											ComboBox{
												AssignTo:     &mw.connSelect,
												Model:        []string{"USB连接", "NetWork连接"},
												CurrentIndex: connIdx,
												OnCurrentIndexChanged: func() {
													// Init底部状态栏
													connIdx = mw.connSelect.CurrentIndex()
													mw.initStatusItem()
													if connIdx == 0 {
														mw.rme.SetVisible(true)
														if len(connDeviceList) > 0 {
															DeviceName = connDeviceList[0].Name
															mw.ipAddr.SetText(DeviceName)
															mw.connBtn.SetText("断开连接")
															mw.ipAddr.SetEnabled(false)
															mw.connBtn.SetEnabled(false)
														}
													} else {
														mw.rme.SetVisible(false)
														mw.ipAddr.SetText("")
														mw.ipAddr.SetEnabled(true)
														mw.connBtn.SetText("连接")
														mw.connBtn.SetEnabled(true)
													}
												},
											},
											// PushButton{
											// 	Text:      "刷新",
											// 	OnClicked: mw.connAdb0,
											// },
										},
									},
									Composite{
										Layout: HBox{},
										Children: []Widget{
											LineEdit{
												AssignTo: &mw.ipAddr,
											},
											PushButton{
												AssignTo:      &mw.connBtn,
												StretchFactor: 8,
												Text:          "连接",
												OnClicked: func() {
													ip := mw.ipAddr.Text()
													if mw.connBtn.Text() == "断开连接" {
														log.Printf("断开[%v]的连接", DeviceName)
														mw.disConnect()
													} else {
														if ip != "" && utils.IsIpv4(ip) {
															DeviceName = ip
															mw.connAdb(ip)
														}
													}
												},
											},
										},
									},
								},
							},
							PushButton{
								Text: "设备信息",
								OnClicked: func() {
									mw.te1.SetVisible(false)
									mw.cs1.SetVisible(true)
									mw.deviceInfo()
								},
							}, PushButton{
								Text: "日志列表",
								OnClicked: func() {
									mw.te1.SetVisible(true)
									mw.cs1.SetVisible(false)
									if cmd, err := mw.fileListDiaLog(); err != nil {
										log.Print(err)
									} else if cmd == walk.DlgCmdOK {
										mw.te1.SetText("意外情况...")
									}
								},
							}, PushButton{
								Text: "日志(实时)",
								OnClicked: func() {
									mw.te1.SetVisible(true)
									mw.cs1.SetVisible(false)
									// go mw.logcatSync()
								},
							},
							PushButton{
								Text: "软件安装",
								OnClicked: func() {
									mw.install()
								},
							},
							Composite{
								AssignTo: &mw.rme,
								Layout:   HBox{MarginsZero: true},
								MinSize:  Size{Height: 20},
								MaxSize:  Size{Height: 22},
								Children: []Widget{
									PushButton{
										Text: "远程开启(临时)",
										OnClicked: func() {
											mw.remoteEnable(false)
										},
									},
									PushButton{
										Text: "远程支持(永久)",
										OnClicked: func() {
											mw.remoteEnable(true)
										},
									},
								},
							},
							PushButton{
								Text: "帮助",
								OnClicked: func() {
									mw.te1.SetVisible(false)
									mw.cs1.SetVisible(true)
									cmd := exec.Command("adb")
									out := command(*cmd, "帮助")
									mw.te1.SetText(out.String())
									mw.te1.SetTextColor(walk.RGB(0, 100, 100))
									mw.te1.SetVisible(true)
									mw.cs1.SetVisible(false)
								},
							},
							GroupBox{
								Layout: VBox{Alignment: AlignHFarVFar},
								Title:  "指令",
								Children: []Widget{
									Composite{
										Layout:  HBox{Spacing: 0},
										MinSize: Size{Height: 50, Width: 50},
										MaxSize: Size{Height: 50, Width: 50},
										Children: []Widget{
											LineEdit{},
											PushButton{
												Text: "发送",
												OnClicked: func() {

												},
											},
										},
									},
								},
							},
							GroupBox{
								ToolTipText: "模拟按键",
								Title:       "模拟按键",
								Layout:      VBox{},
								Children: []Widget{
									Composite{
										Layout: Grid{Columns: 3},
										Children: []Widget{
											PushButton{
												MinSize:   Size{Width: 20},
												Text:      "",
												Alignment: AlignHCenterVNear,
												Enabled:   false,
											},
											PushButton{
												MinSize:   Size{Width: 20},
												Text:      "上",
												Alignment: AlignHCenterVNear,
												OnClicked: func() {
													cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "input", "keyevent", KEYCODE_DPAD_UP)
													command(*cmd, "上")
													mw.refreshScreen()
												},
											},
											PushButton{
												MinSize:   Size{Width: 20},
												Text:      "数字",
												Alignment: AlignHCenterVNear,
												OnClicked: func() {
													mw.numberKeyBoard()
												},
											},
											PushButton{
												MinSize:   Size{Width: 20},
												Text:      "左",
												Alignment: AlignHCenterVNear,
												OnClicked: func() {
													cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "input", "keyevent", KEYCODE_DPAD_LEFT)
													command(*cmd, "左")
													mw.refreshScreen()
												},
											},
											PushButton{
												MinSize:   Size{Width: 20},
												Text:      "确认",
												Alignment: AlignHCenterVNear,
												OnClicked: func() {
													cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "input", "keyevent", "66")
													command(*cmd, "确认")
													mw.refreshScreen()
												},
											},
											PushButton{
												MinSize:   Size{Width: 20},
												Text:      "右",
												Alignment: AlignHCenterVNear,
												OnClicked: func() {
													cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "input", "keyevent", KEYCODE_DPAD_RIGHT)
													command(*cmd, "右")
													mw.refreshScreen()
												},
											},
											PushButton{
												MinSize:   Size{Width: 20},
												Text:      "菜单",
												Alignment: AlignHCenterVNear,
												OnClicked: func() {
													cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "input", "keyevent", "3")
													command(*cmd, "菜单")
													mw.refreshScreen()
												},
											},
											PushButton{
												MinSize:   Size{Width: 20},
												Text:      "下",
												Alignment: AlignHCenterVNear,
												OnClicked: func() {
													cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "input", "keyevent", KEYCODE_DPAD_DOWN)
													command(*cmd, "下")
													mw.refreshScreen()
												},
											},
											PushButton{
												MinSize:   Size{Width: 20},
												Text:      "返回",
												Alignment: AlignHCenterVNear,
												OnClicked: func() {
													cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "input", "keyevent", "4")
													command(*cmd, "返回")
													mw.refreshScreen()
												},
											},
										},
									},
								},
							},
							GroupBox{
								Layout: VBox{},
								Title:  "截屏",
								Children: []Widget{
									Composite{
										Layout: HBox{},
										Children: []Widget{
											PushButton{
												Alignment: AlignHFarVFar,
												Text:      "刷新",
												MinSize:   Size{Width: 10, Height: 10},
												MaxSize:   Size{Width: 40, Height: 15},
												OnClicked: func() {
													mw.refreshScreen()
												},
											},
										},
									},
									Composite{
										Layout: Grid{Columns: 1},
										Children: []Widget{
											ImageView{
												Background:  SolidColorBrush{Color: walk.RGB(244, 244, 244)},
												AssignTo:    &mw.screen,
												Mode:        ImageViewModeZoom,
												ToolTipText: "截屏",
												MinSize:     Size{Width: 250, Height: 280},
											},
										},
									},
								},
							},
						},
					},
					// 功能菜单
					Composite{
						Layout:        VBox{},
						StretchFactor: 4,
						Children: []Widget{
							Composite{
								Layout:  HBox{},
								MinSize: Size{Height: 10},
								Children: []Widget{
									GroupBox{
										Layout: VBox{},
										Title:  "系统操作",
										Children: []Widget{
											Composite{
												Layout: Grid{Columns: 3},
												Children: []Widget{
													PushButton{
														Text:    "启动",
														Enabled: false,
														OnClicked: func() {
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "start-server")
															out := command(*cmd, "启动adb")
															mw.te1.SetText(out.String())
														},
													},
													PushButton{
														Text: "重启设备",
														OnClicked: func() {
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "reboot")
															out := command(*cmd, "重启Android设备")
															mw.te1.SetText(out.String())
														},
													},
													PushButton{
														Text:    "停止",
														Enabled: false,
														OnClicked: func() {
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "stop-server")
															out := command(*cmd, "停止adb")
															mw.te1.SetText(out.String())
														},
													},
													PushButton{
														Text:    "断开连接",
														Enabled: false,
														OnClicked: func() {
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "disconnect")
															out := command(*cmd, "断开所有连接")
															mw.te1.SetText(out.String())
														},
													},
												},
											},
										},
									},
									GroupBox{
										Layout: VBox{},
										Title:  "信发操作",
										Children: []Widget{
											Composite{
												Layout: Grid{Columns: 3},
												Children: []Widget{
													PushButton{
														AssignTo: &mw.irBtn1,
														Text:     "启动",
														OnClicked: func() {
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "am", "start", "-n", InfoReleaseProgrammeName)
															command(*cmd, "启动信发")
															mw.irBtn1.SetEnabled(false)
															mw.initStatusItem()
														},
													},
													PushButton{
														AssignTo: &mw.irBtn2,
														Text:     "重启",
														OnClicked: func() {
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "am", "force-stop", InfoReleasePackageName)
															command(*cmd, "重启信发-关闭")
															cmd = exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "am", "start", "-n", InfoReleaseProgrammeName)
															command(*cmd, "重启信发-打开")
															mw.irBtn1.SetEnabled(false)
															mw.initStatusItem()
														},
													},
													PushButton{
														Text:     "关闭",
														AssignTo: &mw.irBtn3,
														OnClicked: func() {
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "am", "force-stop", InfoReleasePackageName)
															command(*cmd, "停止信发")
															mw.irBtn1.SetEnabled(true)
															mw.irBtn2.SetEnabled(false)
															mw.initStatusItem()
														},
													},
													PushButton{
														AssignTo: &mw.irBtn4,
														Text:     "暂无",
													},
												},
											},
										},
									},
									GroupBox{
										Layout: VBox{},
										Title:  "其他操作",
										Children: []Widget{
											Composite{
												Layout: Grid{Columns: 2},
												Children: []Widget{
													PushButton{
														AssignTo: &mw.fzBtn1,
														Text:     "启动辅助",
														OnClicked: func() {
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "am", "start", "-n", InstallUtilsProgrammeName)
															command(*cmd, "启动辅助")
															mw.initStatusItem()
															mw.fzBtn1.SetEnabled(false)
														},
													},
													PushButton{
														Text: "查看前台Activity",
														OnClicked: func() {
															out := currentActivity()
															mw.showMsg(out.String())
														},
													},
													PushButton{
														AssignTo: &mw.fzBtn2,
														Text:     "关闭辅助",
														OnClicked: func() {
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "am", "force-stop", InstallUtilsPackageName)
															command(*cmd, "关闭辅助")
															mw.initStatusItem()
															mw.fzBtn1.SetEnabled(true)
														},
													},
													PushButton{
														AssignTo: &mw.fzBtn3,
														Text:     "卸载辅助",
														OnClicked: func() {
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "uninstall", InstallUtilsPackageName)
															command(*cmd, "卸载辅助安装")
															// 如果成功则都不能点击
														},
													},
												},
											},
										},
									},
								},
							},
							TextEdit{
								AssignTo: &mw.te1,
								Font:     Font{PointSize: 12},
								Visible:  true,
								ReadOnly: true,
								VScroll:  true,
								HScroll:  true,
							},
							Composite{
								AssignTo:  &mw.cs1,
								Layout:    Grid{Columns: 1},
								Alignment: AlignHNearVNear,
								Visible:   false,
								MinSize:   Size{Width: 700, Height: 750},
								Children: []Widget{
									Composite{
										Layout: HBox{},
										Children: []Widget{
											Label{
												Text:      "设备型号:",
												Font:      Font{PointSize: 14},
												TextColor: walk.RGB(189, 229, 244),
											},
											Label{
												AssignTo: &mw.l1,
												Font:     Font{PointSize: 14},
											},
										},
									},
									Composite{
										Layout: VBox{},
										Children: []Widget{
											Label{
												Text:      "IP地址:",
												Font:      Font{PointSize: 14},
												TextColor: walk.RGB(189, 229, 244),
											},
											Label{
												AssignTo: &mw.l2,
												Font:     Font{PointSize: 10},
											},
										},
									},
									Composite{
										Layout: HBox{},
										Children: []Widget{
											Label{
												Text:      "MAC地址:",
												Font:      Font{PointSize: 14},
												TextColor: walk.RGB(189, 229, 244),
											},
											Label{
												AssignTo: &mw.l3,
												Font:     Font{PointSize: 14},
											},
											Composite{
												Layout: HBox{},
												Children: []Widget{
													Label{Text: "切换网卡"},
													ComboBox{
														Model:    netList,
														AssignTo: &mw.l3cb,
														OnCurrentIndexChanged: func() {
															connIdx := mw.l3cb.CurrentIndex()
															netName := netList[connIdx]
															if netName == "" {
																netName = "wlan0"
															}
															log.Printf("选择网卡：%v", netName)
															cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "cat", "/sys/class/net/"+netName+"/address")
															out := command(*cmd, "切换获取Mac地址")
															mw.l3.SetText(out.String())
														},
													},
												},
											},
										},
									},
									Composite{
										Layout: HBox{},
										Children: []Widget{
											Label{
												Text:      "信发版本:",
												Font:      Font{PointSize: 14},
												TextColor: walk.RGB(189, 229, 244),
											},
											Label{
												AssignTo: &mw.l4,
												Font:     Font{PointSize: 14},
											},
										},
									},
									Composite{
										Layout: HBox{},
										Children: []Widget{
											Label{
												Text:      "辅助安装版本:",
												Font:      Font{PointSize: 14},
												TextColor: walk.RGB(189, 229, 244),
											},
											Label{
												AssignTo: &mw.l5,
												Font:     Font{PointSize: 14},
											},
										},
									},
									Composite{
										Layout: HBox{},
										Children: []Widget{
											Label{
												Text:      "接入网络模式:",
												Font:      Font{PointSize: 14},
												TextColor: walk.RGB(189, 229, 244),
											},
											Label{
												AssignTo: &mw.l6,
												Font:     Font{PointSize: 14},
											},
										},
									},
									Composite{
										Layout: HBox{},
										Children: []Widget{
											Label{
												Text:      "设备分辨率:",
												Font:      Font{PointSize: 14},
												TextColor: walk.RGB(189, 229, 244),
											},
											Label{
												AssignTo: &mw.l7,
												Font:     Font{PointSize: 14},
											},
										},
									},
									Composite{
										Layout: HBox{},
										Children: []Widget{
											Label{
												Text:      "显示屏接入数量:",
												Font:      Font{PointSize: 14},
												TextColor: walk.RGB(189, 229, 244),
											},
											Label{
												AssignTo: &mw.l8,
												Font:     Font{PointSize: 14},
											},
										},
									},
									Composite{
										Layout: HBox{},
										Children: []Widget{
											Label{
												Text:      "安卓版本:",
												Font:      Font{PointSize: 14},
												TextColor: walk.RGB(189, 229, 244),
											},
											Label{
												AssignTo: &mw.l9,
												Font:     Font{PointSize: 14},
											},
										},
									},
								},
							},
						},
					},
				},
			},
		},
		StatusBarItems: []StatusBarItem{
			{
				AssignTo: &mw.sbi,
				Text:     "设备状态",
				Icon:     icon2,
				Width:    180,
				OnClicked: func() {
					// 触发重新连接
					fmt.Println("触发了重新连接")
				},
			},
			{
				AssignTo: &mw.sbi2,
				Text:     "信发运行状态",
				Icon:     icon2,
				Width:    150,
				OnClicked: func() {
					mw.infoReleaseRunStatus()
				},
			},
			{
				AssignTo: &mw.sbi3,
				Text:     "辅助安装",
				Icon:     icon2,
				Width:    80,
				OnClicked: func() {
					var dlg *walk.Dialog
					var acceptPB, cancelPB *walk.PushButton
					if mw.assistInstallRun() {
						mw.sbi3.SetIcon(mw.start)
						mw.sbi3.SetText("辅助安装已安装")
					} else {
						Dialog{
							AssignTo:      &dlg,
							Title:         "辅助安装",
							DefaultButton: &acceptPB,
							CancelButton:  &cancelPB,
							MinSize:       Size{Width: 300, Height: 200},
							Layout:        VBox{Alignment: AlignHCenterVNear},
							Children: []Widget{
								Label{
									Text: "辅助安装没有安装哦！是否立即安装",
								},
								Composite{
									Layout: HBox{},
									Children: []Widget{
										PushButton{
											AssignTo: &acceptPB,
											Text:     "确认",
											OnClicked: func() {
												cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "install", "./apk/InstallUtils_v1.1.0714.apk")
												out := command(*cmd, "安装辅助安装")
												err := cmd.Wait()
												if err != nil {
													log.Printf("辅助安装安装失败: %v", err)
												}
												if strings.Contains(out.String(), "Success") {
													mw.sbi3.SetIcon(mw.start)
													mw.sbi3.SetText("辅助安装已安装")
													mw.showMsg("安装完成")
												}
												dlg.Accept()
											},
										},
										PushButton{
											AssignTo: &cancelPB,
											Text:     "取消",
											OnClicked: func() {
												dlg.Cancel()
											},
										},
									},
								},
							},
						}.Run(mw)
					}
				},
			},
			{
				AssignTo: &mw.sbi4,
				Text:     "是否是M3",
				Icon:     icon2,
				Width:    80,
			},
			{
				AssignTo: &mw.sbi5,
				Text:     "是否ROOT",
				Icon:     icon2,
				Width:    80,
				OnClicked: func() {
					// 触发重新连接
					fmt.Println("触发了重新连接")
				},
			},
		},
		OnDropFiles: func(files []string) {
			mw.te1.SetText(strings.Join(files, "\r\n"))
		},
	}.Run()); err != nil {
		log.Fatal(err)
	}
}

// 初始化底部状态栏
func (mw *MyMainWindow) initStatusItem() {
	// adb连接状态，信发当前运行，辅助安装，是否是M3,是否ROOT
	//sbi, sbi2, sbi3, sbi4, sbi5 *walk.StatusBarItem
	mw.connAdb0()
	mw.infoReleaseRunStatus()
	mw.assistInstallRunStatus()
	mw.isM3()
	mw.isRoot()
}

// IP地址查看
func (mw *MyMainWindow) ipStatusBar() {
	cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "ifconfig")
	cmd1 := exec.Command("findstr", "Bcast")
	commandPip(*cmd, *cmd1, "IP地址状态栏查看")
}

// 是否Root
func (mw *MyMainWindow) isRoot() {
	cmd := exec.Command(AdbToolPath, "root")
	out := command(*cmd, "判断是否ROOT")
	text := out.String()
	text = strings.TrimSpace(text)
	// adbd cannot run as root in production builds
	if text != "restarting adbd as root" && text != "adbd is already running as root" {
		mw.sbi5.SetIcon(mw.stop)
		mw.sbi5.SetText("未ROOT")
	} else {
		mw.sbi5.SetIcon(mw.start)
		mw.sbi5.SetText("已ROOT")
	}
}

// 查看是否是M3
func (mw *MyMainWindow) isM3() {
	cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "getprop", "ro.imyun.board.type")
	out := command(*cmd, "获取设备型号")
	text := out.String()
	if strings.Contains(text, "M3") {

		mw.sbi4.SetIcon(mw.start)
		mw.sbi4.SetText("就是M3")
	} else {
		mw.sbi4.SetIcon(mw.stop)
		mw.sbi4.SetText("不是M3")
	}
}

// 辅助安装运行状态
func (mw *MyMainWindow) assistInstallRunStatus() {
	isInstall := mw.assistInstallRun()
	if isInstall {
		mw.sbi3.SetIcon(mw.start)
		mw.sbi3.SetText("辅助已安装")
		mw.sbi3.SetWidth(120)
	} else {
		mw.sbi3.SetIcon(mw.stop)
		mw.sbi3.SetText("辅助未安装")
	}
}

// 辅助安装状态
func (mw *MyMainWindow) assistInstallRun() bool {
	// 判断辅助安装是否安装
	cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "pm", "list", "packages", "-3", "installutils")
	out := command(*cmd, "辅助安装是否安装")
	return out.String() != ""
}

// 信发运行状态
func (mw *MyMainWindow) infoReleaseRunStatus() {
	out := currentActivity()
	text := out.String()
	log.Printf("信发运行状态: %v", text)
	if strings.Contains(text, InfoReleasePlayerName) || strings.Contains(text, InfoReleaseProgrammeName) {
		mw.sbi2.SetIcon(mw.start)
		mw.sbi2.SetText("信发正在运行")
		mw.irBtn1.SetEnabled(false)
	} else {
		mw.sbi2.SetIcon(mw.stop)
		mw.sbi2.SetText("信发未运行")
		mw.irBtn1.SetEnabled(true)
	}
}

// 刷新截屏
func (mw *MyMainWindow) refreshScreen() {
	mw.refreshScreen2()
	mw.refreshScreen2()
}

func (mw *MyMainWindow) refreshScreen2() {
	// 修改文件名称
	err := os.Remove("tmp/screen/sc.png")
	if err != nil {
		log.Printf("删除文件名错误：%v", err)
	}
	err = os.Rename("tmp/screen/temp.png", "tmp/screen/sc.png")
	if err != nil {
		log.Printf("修改文件名错误：%v", err)
	}
	// 获取截屏
	cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "exec-out", "screencap", "-p")
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	sc, _ := os.OpenFile("tmp/screen/temp.png", os.O_RDWR|os.O_CREATE|os.O_SYNC, 0755)
	defer sc.Close()
	cmd.Stdout = sc
	cmd.Stderr = sc
	err = cmd.Run()
	if err != nil {
		log.Printf("截屏文件获取失败: %v", err)
	}
	img, err := walk.NewImageFromFileForDPI("tmp/screen/sc.png", 96)
	fmt.Println("渲染sc")
	if err != nil {
		log.Printf("截屏文件不存在: %v", err)
	}
	fmt.Println("显示sc")
	mw.screen.SetImage(img)
}

// 数字键盘
func (mw *MyMainWindow) numberKeyBoard() (int, error) {
	var dlg *walk.Dialog
	var acceptPB, cancelPB *walk.PushButton
	return Dialog{
		AssignTo:      &dlg,
		Title:         "模拟数字键",
		DefaultButton: &acceptPB,
		CancelButton:  &cancelPB,
		MinSize:       Size{Width: 500, Height: 400},
		Layout:        VBox{Alignment: AlignHCenterVNear},
		Children: []Widget{
			Composite{
				Layout: VBox{},
				Children: []Widget{
					Composite{
						Layout: HBox{},
						Children: []Widget{
							LineEdit{
								Text: "键盘输入批量发送",
							},
							PushButton{
								Text: "发送",
							},
						},
					},
					Composite{
						Layout: Grid{Columns: 3},
						Children: []Widget{
							PushButton{Text: "1"},
							PushButton{Text: "2"},
							PushButton{Text: "3"},
							PushButton{Text: "4"},
							PushButton{Text: "5"},
							PushButton{Text: "6"},
							PushButton{Text: "7"},
							PushButton{Text: "8"},
							PushButton{Text: "9"},
							PushButton{Text: "0"},
						},
					},
				},
			},
		},
	}.Run(mw)
}

// 远程开启USB
func (mw *MyMainWindow) remoteEnable(forerver bool) (int, error) {
	var acceptPB, cancelPB *walk.PushButton
	return Dialog{
		AssignTo:      &mw.dlgrm,
		Title:         "网络调试",
		DefaultButton: &acceptPB,
		CancelButton:  &cancelPB,
		MinSize:       Size{Width: 300, Height: 250},
		Layout:        VBox{Alignment: AlignHCenterVNear},
		Children: []Widget{
			Label{
				Text: "您将开启远程调试功能，方便后期对设备的维护,\n 本操作一本万利，建议开启\n只能在USB调试模式下开启",
				Font: Font{PointSize: 14},
			},
			Composite{
				Layout: HBox{Alignment: AlignHCenterVFar},
				Children: []Widget{
					PushButton{
						AssignTo: &acceptPB,
						Text:     "开启",
						MinSize:  Size{Height: 60, Width: 100},
						MaxSize:  Size{Height: 60, Width: 100},
						OnClicked: func() {
							mw.dlgrm.Cancel()
							mw.remoteEnableEv(forerver)
						},
					}, PushButton{
						AssignTo: &acceptPB,
						Text:     "取消",
						MinSize:  Size{Height: 60, Width: 100},
						MaxSize:  Size{Height: 60, Width: 100},
						OnClicked: func() {
							mw.dlgrm.Cancel()
						},
					},
				},
			},
		},
	}.Run(mw)
}

// 远程开启USB方式
func (mw *MyMainWindow) remoteEnableEv(forever bool) {
	mw.te1.SetVisible(true)
	mw.cs1.SetVisible(false)
	cmd := exec.Command(AdbToolPath, "root")
	out := command(*cmd, "Adb提权")
	text := out.String()
	mw.te1.SetText(mw.te1.Text() + "\r\n" + fmt.Sprintf("Adb提权%v\r\n", text))
	// restarting adbd as root
	// adbd is already running as root
	// 提权失败直接结束
	text = strings.TrimSpace(text)
	if text != "restarting adbd as root" && text != "adbd is already running as root" {
		// adbd cannot run as root in production builds
		mw.showMsg("此设备未ROOT,请ROOT后重试")
		return
	}
	cmd = exec.Command(AdbToolPath, AdbToolShell, "setprop", "service.adb.tcp.port", "5555")
	out = command(*cmd, "配置adbd调试端口")
	text = out.String()
	mw.te1.SetText(mw.te1.Text() + "\r\n" + fmt.Sprintf("配置adbd调试端口%v\r\n", text))
	// setprop service.adb.tcp.port -1 adb usb调试功能
	// 永久
	// mount -o rw,remount /system
	// setprop service.adb.tcp.port 5555
	//
	// 删除文档最后一行 adb shell "sed -i '$d' /system/build.prop"
	// adb shell "sed -i '$aservice.adb.tcp.port=5555' /system/build.prop"
	if forever {
		cmd = exec.Command(AdbToolPath, AdbToolShell, "mount", "-o", "rw,remount", "/system")
		out = command(*cmd, "挂载系统分区")
		text = out.String()
		mw.te1.SetText(mw.te1.Text() + "\r\n" + fmt.Sprintf("挂载系统分区%v\r\n", text))
		// adb shell "echo service.adb.tcp.port=5555 >> /system/build.prop"
		cmd := exec.Command(AdbToolPath, AdbToolShell, `echo service.adb.tcp.port=5555 >> /system/build.prop`)
		out := command(*cmd, "写入永久文件")
		text := out.String()
		mw.te1.SetText(mw.te1.Text() + "\r\n" + fmt.Sprintf("写入永久文件，重启后不丢失%v\r\n", text))
	}
	time.Sleep(time.Second * 2)
	// adb tcpip 5555
	cmd = exec.Command(AdbToolPath, "tcpip", "5555")
	out = command(*cmd, "重启ADB网络调试")
	text = out.String()
	mw.te1.SetText(mw.te1.Text() + "\r\n" + fmt.Sprintf("开启本机adb网络调试%v\r\n结束配置！", text))

}

// 基础命令
func command(cmd exec.Cmd, title string) bytes.Buffer {
	var out bytes.Buffer
	cmd.Stdout = &out
	fmt.Println("准备执行[" + title + "]命令")
	// 隐藏CMD窗口
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	// cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 0x8000000}
	err := cmd.Run()
	if err != nil {
		log.Println("命令执行错误", err)
	}
	fmt.Println("[" + title + "]执行完毕")

	return out
}

func currentActivity() bytes.Buffer {
	cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "dumpsys", "activity", "activities")
	cmd1 := exec.Command("findstr", "mFocusedActivity")
	return commandPip(*cmd, *cmd1, "获取前台Activity")
}

// 管道command
func commandPip(cmd exec.Cmd, cmd1 exec.Cmd, title string) bytes.Buffer {
	var out bytes.Buffer
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	cmd1.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	cmd1.Stdin, _ = cmd.StdoutPipe()
	cmd1.Stdout = os.Stdout
	cmd1.Stderr = os.Stderr
	cmd1.Stdout = &out
	cmd1.Start()
	fmt.Println("准备执行[" + title + "]命令(管道模式)")
	cmd.Run()
	err := cmd1.Wait()
	if err != nil {
		log.Println("命令执行错误(管道模式)", err)
	}
	fmt.Println("[" + title + "]执行完毕(管道模式)")
	return out
}

// 设备列表查看
func adbDeviceList() {
	cmd := exec.Command(AdbToolPath, "devices")
	out := command(*cmd, "设备列表查看")
	text := out.String()
	list := strings.Split(text, "\r\n")
	size := len(list)
	log.Printf("当前连接的设备长度是: %v", size)
	if size > 3 {
		log.Printf("设备列表：%v", list)
		for _, v := range list[1:] {
			if v == "" {
				log.Printf("无效设备列表: [%v]\n", v)
			} else {
				device := strings.Split(v, "\t")
				connDeviceList = append(connDeviceList, Device{device[0], device[1]})
			}
		}
	}
}

// 断开连接
func (mw *MyMainWindow) disConnect() {
	cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "disconnect")
	command(*cmd, "断开设备连接")
	mw.ipAddr.SetEnabled(true)
	mw.connBtn.SetText("连接")
	mw.connSelect.SetEnabled(true)
}

// 设备连接[USB]
func (mw *MyMainWindow) connAdb0() {
	connDeviceList = []Device{}
	adbDeviceList()
	fmt.Printf("设备连接列表：%v\n", connDeviceList)
	if connIdx == 1 {
		mw.sbi.SetIcon(mw.stop)
		mw.sbi.SetText("未连接")
		mw.ipAddr.SetEnabled(true)
		mw.connBtn.SetText("连接")
	}
}

// 设备连接[IP]
func (mw *MyMainWindow) connAdb(ip string) {
	// 判断ip是否能通
	if !utils.Isping(ip) {
		mw.showMsg("IP无法联通，请查看后重试")
		return
	}
	cmd := exec.Command(AdbToolPath, "connect", ip)
	out := command(*cmd, "设备连接[IP]")
	text := out.String()
	if strings.Contains(text, "connected to") {
		mw.ipAddr.SetEnabled(false)
		mw.connBtn.SetText("断开连接")
		mw.connSelect.SetEnabled(false)
	} else {
		log.Printf("%v连接错误", ip)
	}
}

// 设备信息
func (mw *MyMainWindow) deviceInfo() {
	// cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName,"shell", "cat", "/system/build.prop")
	// out := command(*cmd, "获取设备信息")
	// adb shell getprop ro.imyun.board.type
	// adb shell getprop ro.product.model
	cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "getprop", "ro.imyun.board.type")
	out := command(*cmd, "获取设备型号")
	mw.l1.SetText(out.String())

	cmd = exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "ifconfig")
	cmd1 := exec.Command("findstr", "addr")
	out = commandPip(*cmd, *cmd1, "IP地址")
	mw.l2.SetText(out.String())

	cmd = exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "cat", "/sys/class/net/wlan0/address")
	out = command(*cmd, "Mac地址")
	mw.l3.SetText(out.String())

	cmd = exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "ls", "/sys/class/net/")
	out = command(*cmd, "获取网卡列表")
	text := out.String()
	netList = strings.Split(text, "\r\n")
	mw.l3cb.SetModel(netList)

	// adb shell dumpsys package com.kiton.wang.message.video.SendByGroup | findstr
	cmd = exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "dumpsys", "package", InfoReleasePackageName)
	cmd1 = exec.Command("findstr", "versionName")
	out = commandPip(*cmd, *cmd1, "信发版本")
	text = out.String()
	if text != "" {
		strs := strings.Split(text, "=")
		mw.l4.SetText(strs[1])
	}

	cmd = exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "dumpsys", "package", InstallUtilsPackageName)
	cmd1 = exec.Command("findstr", "versionName")
	out = commandPip(*cmd, *cmd1, "辅助安装版本")
	text = out.String()
	if text != "" {
		strs := strings.Split(text, "=")
		mw.l5.SetText(strs[1])
	}

	cmd = exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "wm", "size")
	out = command(*cmd, "显示屏分辨率")
	mw.l7.SetText(out.String())

	cmd = exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "dumpsys", "displays")
	cmd1 = exec.Command("findstr", "mDisplayId")
	out = command(*cmd, "显示屏支持数量")
	text = out.String()
	displayList = strings.Split(text, "\r\n")
	mw.l8.SetText(strconv.Itoa(len(displayList)))

	cmd = exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "getprop", "ro.build.version.release")
	out = command(*cmd, "Android版本")
	mw.l9.SetText(out.String())

}

// 获取路径下所有文件
func files() (list []string, err error) {
	cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "ls", "/sdcard/Android/data/com.kiton.wang.message.video.SendByGroup/files/info/")
	out := command(*cmd, "获取日志文件")
	text := out.String()
	str := strings.Split(text, "\r\n")
	if len(str) > 0 {
		return str, nil
	}
	return str, errors.New("错误")
}

// 实时日志
func (mw *MyMainWindow) logcatSync() {
	cmd := exec.Command(AdbToolPath, "logcat")
	//StdoutPipe方法返回一个在命令Start后与命令标准输出关联的管道。Wait方法获知命令结束后会关闭这个管道，一般不需要显式的关闭该管道。
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Println("cmd.StdoutPipe: ", err)
	}
	cmd.Stderr = os.Stderr
	err = cmd.Start()
	if err != nil {
		fmt.Println("cmd.Run: ", err)
	}
	//创建一个流来读取管道内内容，这里逻辑是通过一行一行的读取的
	reader := bufio.NewReader(stdout)
	//实时循环读取输出流中的一行内容
	for {
		line, err2 := reader.ReadString('\n')
		if err2 != nil || io.EOF == err2 {
			break
		}
		mw.te1.SetText(mw.te1.Text() + fmt.Sprintf("\n%v", line))
	}
	err = cmd.Wait()
	if err != nil {
		fmt.Println("cmd.Run: ", err)
	}
}

// 信息发布日志文件
func infoReleaseLog(fileName string) []byte {
	fmt.Println(fileName)
	cmd := exec.Command(AdbToolPath, AdbToolPoint, DeviceName, "shell", "cat", "/sdcard/Android/data/com.kiton.wang.message.video.SendByGroup/files/info/"+fileName)
	out := command(*cmd, "日志文件查看")
	return out.Bytes()
}

// 日志文件列表对话框
func (mw *MyMainWindow) fileListDiaLog() (int, error) {
	var dlg *walk.Dialog
	var acceptPB, cancelPB *walk.PushButton
	var AssignToComboBox *walk.ComboBox
	index := 0
	list, err := files()
	length := len(list)
	log.Println("日志文件的长度是:", length)
	if length == 1 && list[0] == "" {
		mw.showMsg("日志文件不存在")
		return -1, nil
	}
	if err != nil {
		log.Println("获取日志文件列表错误")
	}
	mw.te1.SetText(string(infoReleaseLog(list[index])))
	return Dialog{
		AssignTo:      &dlg,
		Title:         "选择日志",
		DefaultButton: &acceptPB,
		CancelButton:  &cancelPB,
		Size:          Size{Width: 120, Height: 80},
		Layout:        VBox{},
		Children: []Widget{
			Composite{
				Layout: HBox{},
				Children: []Widget{
					ComboBox{
						AssignTo:     &AssignToComboBox,
						Model:        list,
						CurrentIndex: index,
						OnCurrentIndexChanged: func() {
							index = AssignToComboBox.CurrentIndex()
						},
					},
					PushButton{
						Text: "下载",
						OnClicked: func() {
							fileName := list[index]
							log.Println(fileName, "日志文件下载中")
							err := ioutil.WriteFile(fileName, infoReleaseLog(fileName), 0644)
							if err != nil {
								log.Fatal("日志文件下载错误", err)
							}
						},
					},
				},
			},
			Composite{
				Layout: HBox{},
				Children: []Widget{
					PushButton{
						AssignTo: &acceptPB,
						Text:     "确认",
						OnClicked: func() {
							dlg.Cancel()
							mw.te1.SetText(string(infoReleaseLog(list[index])))
						},
					},
					PushButton{
						AssignTo: &cancelPB,
						Text:     "取消",
						OnClicked: func() {
							dlg.Cancel()
						},
					},
				},
			},
		},
	}.Run(mw)
}

// 显示弹出消息框
func (mw *MyMainWindow) showMsg(messgae string) {
	walk.MsgBox(mw, "提示", messgae, walk.MsgBoxIconInformation)
}

// 安装软件
func (mw *MyMainWindow) install() (int, error) {
	var dlg *walk.Dialog
	var acceptPB, cancelPB *walk.PushButton

	index := 0

	list, err := files()
	if err != nil {
		log.Fatal("获取日志文件列表错误")
	}
	mw.te1.SetText(string(infoReleaseLog(list[index])))
	return Dialog{
		AssignTo:      &dlg,
		Title:         "软件安装",
		DefaultButton: &acceptPB,
		CancelButton:  &cancelPB,
		MinSize:       Size{Width: 500, Height: 400},
		Layout:        VBox{Alignment: AlignHCenterVNear},
		Children: []Widget{
			Composite{
				Layout: Grid{Columns: 2},
				Children: []Widget{
					Composite{
						Layout: VBox{},
						Children: []Widget{
							Label{
								Text: "项目",
							},
							ComboBox{
								Model: []string{"a", "b", "c"},
							},
						},
					},
					Composite{
						Layout: VBox{},
						Children: []Widget{
							Label{
								Text: "版本",
							},
							ComboBox{
								Model: []string{"a", "b", "c"},
							},
						},
					},
				},
			},
			TextEdit{
				Text: "信息\n信息\n信息\n信息\n信息\n",
			},
			Composite{
				Layout: HBox{},
				Children: []Widget{
					ProgressBar{
						MinValue: 0,
						MaxValue: 100,
						Value:    100,
					},
					PushButton{
						Alignment: AlignHFarVNear,
						MinSize:   Size{Width: 40},
						Text:      "立即安装",
					},
				},
			},
		},
	}.Run(mw)
}
